package com.lc202309;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Description:
 *
 * @Create 2023/8/27 23:27
 * @Version 1.0
 */
public class Solution57 {
    public static int[][] insert(int[][] intervals, int[] newInterval) {
        if (intervals.length == 0) {
            int [][] res = new int [1][2];
            res[0][0]=newInterval[0];
            res[0][1]=newInterval[1];
            return res;
        }
        List<List<Integer>> lists = new ArrayList<>();
        for (int[] interval : intervals) {
            List<Integer> nums = new ArrayList<>();
            nums.add(interval[0]);
            nums.add(interval[1]);
            lists.add(nums);
        }
        List<Integer> nums1 = new ArrayList<>();
        nums1.add(newInterval[0]);
        nums1.add(newInterval[1]);
        lists.add(nums1);
        lists.sort(Comparator.comparingInt(o -> o.get(0)));
        int start = 0;
        int end = 0;
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            if (i == 0) {
                start = lists.get(0).get(0);
                end = lists.get(0).get(1);
                continue;
            }
            if (end < lists.get(i).get(0)) {
                List<Integer> nums = new ArrayList<>();
                nums.add(start);
                nums.add(end);
                res.add(nums);
                start = lists.get(i).get(0);
                end = lists.get(i).get(1);
                continue;
            }
            if (end < lists.get(i).get(1)) {
                end = lists.get(i).get(1);
            }
        }
        int[][] ints = new int[res.size() + 1][2];
        for (int i = 0; i < res.size(); i++) {
            ints[i][0] = res.get(i).get(0);
            ints[i][1] = res.get(i).get(1);
        }
        ints[res.size()][0] = start;
        ints[res.size()][1] = end;
        return ints;
    }

    public static void main(String[] args) {
        int[][] intervals = {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};
        int[] newInterval = {4, 8};

        for (int[] ints : insert(intervals,newInterval)) {
            System.out.println(ints[0] + "," + ints[1]);
        }
    }
}
